<template>
  <div>
    <!-- 面包屑导航 -->
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
          </el-breadcrumb>

        
    <!-- 卡片视图 -->
    <el-card>
      <!-- 黄色组件 -->
       <el-alert closable show-icon title="注意！只允许为第三级分类添加相关参数" type="warning"></el-alert>

       <!-- 选择商品分类区域 -->
       <el-row>
         <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择框  选择商品分类     options指定数据源  props配置 clearable允许清空选择器-->
           <el-cascader v-model="cascaderModel" :options="catelist" :props="cateProps" @change="handleChange"></el-cascader>
         </el-col>
       </el-row>

       <!-- tabs页签 -->
       <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="用户管理" name="many">
          <!-- 添加参数的按钮 -->
           <el-button type="primary" size="mini" :disabled="isBtnDisbald" @click="adddialogVisible = true">添加参数</el-button>
           <!-- 动态参数表格 -->
           <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染tag标签 -->
                    <el-tag @close="handlecolse(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加的按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
            <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                 <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDirlog(scope.row.attr_id)">编辑</el-button>
                 <el-button size="mini" type="danger" icon="el-icon-delete" @click="delremoveParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
           </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="配置管理" name="only">
          <!-- 添加属性的按钮 -->
          <el-button type="primary"  size="mini" :disabled="isBtnDisbald"  @click="adddialogVisible = true">添加属性</el-button>

           <!-- 静态参数表格 -->
           <el-table :data="onlyTableData" border stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染tag标签 -->
                    <el-tag @close="handlecolse(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加的按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
            <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="属性名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                 <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDirlog">编辑</el-button>
                 <el-button size="mini" type="danger" icon="el-icon-delete" @click="delremoveParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
           </el-table>
        </el-tab-pane>   
      </el-tabs>
    </el-card>





  <!-- 添加参数 -->
      <el-dialog
      :title="'添加'+titleDialog"
      :visible.sync="adddialogVisible"
      width="30%"
      @close="addDialogClose"
      >
      <!-- 添加参数的对话框from表单 -->
          <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="80px">
            <el-form-item :label="titleDialog" prop="attr_name">
              <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>



    <!-- 修改参数对话框 -->
      <el-dialog
      :title="'修改'+titleDialog"
      :visible.sync="EditdialogVisible"
      width="30%"
      @close="editDialogClose"
      >
      <!-- 添加参数的对话框from表单 -->
          <el-form ref="EditFormRef" :rules="EditFormRules" :model="EditForm" label-width="80px">
            <el-form-item :label="titleDialog" prop="attr_name">
              <el-input v-model="EditForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'myParams',
    data(){
      return {
        // 商品分类列表
        catelist:[],
        // 级联选择框的配置对象
        cateProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children'
        },
        // 级联选择器 双向绑定到的数据
        cascaderModel:[],
        // tabs页签选择器 被激活的页签的名称
        activeName:'many',
        // 获取到的动态参数的数据
        manyTableData:[],
        // 获取到的静态属性的数据
        onlyTableData:[],
        // 添加动态或静态的对话框 的显示和隐藏
        adddialogVisible:false,
        // 添加参数的表单数据对象
        addForm:{
          attr_name:''
        },
        //添加表单的验证规则对象 
        addFormRules:{
          attr_name:[
            {required:true,message:'请输入参数名称',tirgger:'blur'}
          ]
        },
        // 编辑表单对话框的显示和隐藏
        EditdialogVisible:false,
        // 修改对话框的数据绑定对象
        EditForm:{},
        // 修改表单的验证规则对象
        EditFormRules:{
          attr_name:[
            {required:true,message:'请输入参数名称',tirgger:'blur'}
          ]
        },
      

      }
    },
    created(){
      this.getCateList()
    },
    methods:{
      // 获取所有的商品分类列表
     async getCateList(){
      const {data:res} = await this.$axios.get('categories')
      if(res.meta.status !== 200) return this.$message.error('获取参数失败！！')
      this.catelist=res.data
      
      },
      // 级联选择器选中项发生变化触发函数
      async handleChange(){
        this.getParamsDate()
      },
      // 获取参数列表数据
      async getParamsDate(){
           // 判断是不是选中的三级分类 如果不是三级分类 就自动清空
        if(this.cascaderModel.length !== 3){
          this.cascaderModel = []
          this.manyTableData=[]
          this.onlyTableData=[]
          return
        }
        // 根据所选的分类ID ,和当前所处的面板 获取对应的参数
       const {data:res} = await this.$axios.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
       if(res.meta.status !== 200) return this.$message.error('获取参数失败!!')
      //  将里面的attr_vals 转换为数组
          res.data.forEach(item=>{
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' '):[];
            // 为每一行数据增加两条数据
            item.inputVisible=false;
            // 增加文本框中输入的值
            item.inputValue=''
          })
          // console.log(res);
          // 判断获取到的数据是many动态还是only静态
          if(this.activeName=='many'){
            this.manyTableData=res.data
          }else{
            this.onlyTableData=res.data
          }
      },
      // Tab点击事件的处理函数
      handleTabClick(){
        this.getParamsDate()
        console.log(this.activeName);
      },
      // 监听对话框的关闭事件
      addDialogClose(){
        this.$refs.addFormRef.resetFields()
      },
      // 点击按钮添加参数
       addParams(){
        this.$refs.addFormRef.validate(async valid=>{
          if(!valid) return 
          const {data:res} = await this.$axios.post(`categories/${this.cateId}/attributes`,{
            attr_name:this.addForm.attr_name,
            attr_sel:this.activeName
          })
          if(res.meta.status !== 201) return this.$message.error('添加参数失败')
          console.log(res)



          this.$message.success('添加参数成功')
          this.adddialogVisible=false
          // 刷新列表
          this.getParamsDate()
        })
      },
      // 点击按钮展示修改对话框
     async showEditDirlog(id){
        console.log(id);
          const {data:res} = await this.$axios.get(`categories/${this.cateId}/attributes/${id}`,{params:{attr_sel:this.activeName}})
          if(res.meta.status !== 200) return this.$message.error('获取参数失败！')
          this.EditForm=res.data
          this.EditdialogVisible=true 
      },
      // 监听修改对话框的关闭事件
      editDialogClose(){
         this.$refs.EditFormRef.resetFields()
      },
      // 点击确定 修改
       EditParams(){
        this.$refs.EditFormRef.validate(async valid=>{
          if(!valid) return
          const {data:res} = await this.$axios.put(`categories/${this.cateId}/attributes/${this.EditForm.attr_id}`,
          {
            attr_name:this.EditForm.attr_name,
            attr_sel:this.activeName
            })
            if(res.meta.status !== 200) return this.$message.error('修改失败！！')
            this.$message.success('修改成功！！')

          //关闭对话框
          this.EditdialogVisible=false
          // 刷新参数
          this.getParamsDate()

        })
      },
      // 删除参数
      async delremoveParams(id){
         // 弹出对话框是否要删除
           // 根据弹框提示用户是否要删除
            const commitFrom = await this.$confirm( "此操作将永久删除该参数，是否继续?","提示",{
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning", 
              }
            ).catch(err=>err);
            if(commitFrom !== 'confirm') return 
           const {data:res} = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`)
           if(res.meta.status !== 200) return this.$message.error('删除失败请重试！！')
           this.$message.success('删除成功！')
           console.log(res);
          // 刷新参数
          this.getParamsDate()
      },
      // 文本失去焦点 或者回车抬起都会触发
      async handleInputConfirm(row){
       if(row.inputValue.trim().length === 0) {
        row.inputValue=''
        row.inputVisible=false
        return
       }
      //  如果没有return出去 就进入后取得处理· 
      row.attr_vals.push(row.inputValue)
        row.inputValue=''
        row.inputVisible=false
        // 发起请求将这次操作保存到数据库
        this.seaveattrLog(row)
       
      },
      async seaveattrLog(row){
         const {data:res}=await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        })
        if(res.meta.status !==200) return this.$message.error('需改参数项失败')
        this.$message.success('需改参数项成功！')
      },
      showInput(row) {
        row.inputVisible = true;
        // ===================================================================================
        this.$nextTick(()=>{
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 删除对应的tag参数和选项
      handlecolse(i,row){
        // 根据索引删除数组中的当前这个索引
        row.attr_vals.splice(i,1)
        // 调用修改操作保存到数据库
         this.seaveattrLog(row)
      }
    },
    computed:{
      // 如果需要被禁用 则返回true 否则 返回false
      // 如果选中的不是三级分类 就禁用按钮
      isBtnDisbald(){
        if(this.cascaderModel.length !== 3){
          return true
        }else{
          return false
        }
      },
      // 取值选中的三级分类的ID
      cateId(){
        if(this.cascaderModel.length === 3){
          console.log(this.cascaderModel[2]);
          return this.cascaderModel[2]
        }
        return null
      },
      // 动态计算标题的文本
      titleDialog(){
        if(this.activeName == 'many'){
          return '动态参数'
        }
        return '静态属性'
      }
    }
}
</script>

<style scoped>
.el-alert{
  margin-bottom:15px
}
.el-cascader{
  width: 20%;
}
.el-tag{
  margin: 10px;
}
.input-new-tag{
  width: 120px;  
}
</style>